<template>
  <el-dialog v-model="dialogFormVisible" :title="title" width="800">
    <el-form :model="form" ref="formRef" label-width="auto" style="max-width: 800px" :rules="rules">
      <div class="form-scroll">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="标签名称" prop="name">
              <el-input v-model="form.name" placeholder="请填写标签名称" />
            </el-form-item>
          </el-col>
        </el-row>
      </div>
    </el-form>
    <div>
      <el-button type="primary" @click="onSubmit">{{ isEdit? '编辑': '新增' }}</el-button>
      <el-button @click="dialogFormVisible = false">取消</el-button>
    </div>
  </el-dialog>
</template>

<script setup>
// 方法
import { ref, defineExpose, defineEmits } from 'vue'

// 接口
// import { addLaber, updateLaber } from '@/api/goods/label/index.js'

const instance = getCurrentInstance();
const { proxy } = instance || {};

// 显示表单
const dialogFormVisible = ref(false)
const title = ref('新增标签')
const isEdit = ref(false)
const formRef = ref(null)
// 表单
const form = ref({
  name: '',
  id: '',
})
// 验证
const rules = ref({
  name: [
    { required: true, message: '请填写标签名称', trigger: 'blur' }
  ]
})

const emits = defineEmits(['change'])

// 打开方法
const open = () => {
  for (let i in form.value) {
    form.value[i] = ''
  }
  dialogFormVisible.value = true
  isEdit.value = false
  title.value = '新增标签'
}
// 编辑
const edit = (data) => {
  for (let i in form.value) {
    form.value[i] = data[i]
  }
  isEdit.value = true
  dialogFormVisible.value = true
  title.value = '编辑标签'
}
// 关闭方法
const close = () => {
  dialogFormVisible.value = false
}

// 提交
const onSubmit = async () => {

  await formRef.value.validate((valid, fields) => {
    if (valid) {
      if(form.value.id) {
        updateLaber(form.value).then(res => {
          if(res.code === 200) {
            proxy.$modal.msgSuccess(title.value + '成功');
            close()
            emits('change')
          }
        })
      }else {
        addLaber(form.value).then(res => {
          if(res.code === 200) {
            proxy.$modal.msgSuccess(title.value + '成功');
            close()
            emits('change')
          }
        })
      }
    }
  })
}

defineExpose({
  open, close, edit
})

</script>

<style scoped lang="scss">

</style>
